package me.healthcare.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import me.healthcare.app.R;
import me.healthcare.common.ActionBarUtils;
import me.healthcare.webserivce.WebService;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private long back_pressed = 0;
	private long patient_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set View to login.xml
		setContentView(R.layout.login_screen);

		ActionBarUtils.remade(this,
				getResources().getString(R.string.activity_login));

		//

		// view variables
		TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
		TextView forgetPasswordScreen = (TextView) findViewById(R.id.link_to_reset_password);
		Button loginButton = (Button) findViewById(R.id.btnLogin);

		loginButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO validate inputs, call login methods on server and
				// response.

				EditText etUsername = (EditText) findViewById(R.id.etUsername);
				EditText etPassword = (EditText) findViewById(R.id.etPassword);
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();

				if (username.contains("doc")) {
					Intent i = new Intent(LoginActivity.this
							.getApplicationContext(), DoctorActivity.class);
					startActivity(i);
					return;
				}

				new Login().execute("http://" + WebService.HOST_IP
						+ "/sworldwebservice/sworld/auth/loginPatients/"
						+ username + "/" + password);

				Log.d("PATIENT_ID", patient_id + "");
				if (patient_id <= 0) {
					Toast.makeText(LoginActivity.this,
							"Sai thông tin đăng nhập, vui lòng thử lại ",
							Toast.LENGTH_LONG).show();
				} else {

					Intent i = new Intent(LoginActivity.this
							.getApplicationContext(), PatientActivity.class);
					i.putExtra("id", patient_id);
					;
					startActivity(i);
				}
			}
		});

		// listening to register new account link.
		registerScreen.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(LoginActivity.this
						.getApplicationContext(), RegisterActivity.class);
				LoginActivity.this.startActivity(i);
			}
		});

		// listening to forget password link.
		forgetPasswordScreen.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(LoginActivity.this
						.getApplicationContext(), ForgetPasswordActivity.class);
				LoginActivity.this.startActivity(i);
			}
		});
	}

	@Override
	public void onBackPressed() {
		if (back_pressed + 2000 > System.currentTimeMillis())
			super.onBackPressed();
		else
			Toast.makeText(getBaseContext(), R.string.on_back_press,
					Toast.LENGTH_SHORT).show();
		back_pressed = System.currentTimeMillis();
	}

	class Login extends AsyncTask<String, Void, Long> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected Long doInBackground(String... data) {
			try {
				URL url = new URL(data[0]);
				Log.d("URL", url.toString());
				URLConnection jc;
				long id = (long) -1;
				jc = url.openConnection();
				InputStream is = jc.getInputStream();

				// doc du lieu
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();

				String jsonTxt = sb.toString(); // doc StringBuilder vao
												// chuoi
				JSONObject jj = new JSONObject(jsonTxt);
				String status = jj.getString("status");

				Log.d("STATUS", status);
				if (!status.equalsIgnoreCase("SUCCESS")) {
					id = (long) 0;
				}
				JSONObject obj = jj.getJSONObject("obj");

				id = obj.getLong("id");
				Log.d("PATIENT_ID_END", patient_id + "");
				return id;
			} catch (Exception e) {
				return (long) -1;
			}
		}

		protected void onPostExecute(Long id) {
			Log.d("patient_id_atPost_Execute", id + "");
			patient_id = id;
		}
	}
}
